import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => {
    // 从localStorage恢复状态
    const isAdmin = localStorage.getItem('isAdmin') === 'true'
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null')
    const token = localStorage.getItem('token')

    return {
      isAuthenticated: !!token,
      isAdmin: isAdmin,
      userInfo: userInfo,
      token: token,
      isLogin: !!token,
    }
  },
  actions: {
    setUser(data) {
      this.token = data.token || ''
      this.isLogin = true
      this.isAdmin = data.isAdmin 
      this.userInfo = {
        employeeNo: data.employeeNo,
        name: data.name,
        employeeId: data.employeeId,
        ...data
      }
      
      // 将用户信息保存到localStorage
      if(data.token) localStorage.setItem('token', data.token)
      localStorage.setItem('isAdmin', data.isAdmin.toString())
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    logout() {
      this.token = ''
      this.isLogin = false
      this.isAdmin = false
      this.userInfo = null
      
      // 清除localStorage中的数据
      localStorage.removeItem('token')
      localStorage.removeItem('isAdmin')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('employeeNo')
      localStorage.removeItem('employeeId')
      localStorage.removeItem('name')
    },
  },
})
